package com.itheima.aop;

import com.itheima.mapper.EmpLoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


@Slf4j
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private EmpLoginMapper empLoginMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object loginAspect(ProceedingJoinPoint pjp) throws Throwable {
        // Emp[] args =(Emp[]) pjp.getArgs();
        Object[] args =pjp.getArgs();
        String username=null;
        String password=null;
        if (args != null && args.length > 0 && args[0] instanceof Emp) {
            Emp emp =(Emp) args[0];
            username = emp.getUsername();
            log.info("用户名：{}",username);
            password = emp.getPassword();
            log.info("密码：{}",password);
        }
        //操作时间
        LocalDateTime loginTime=LocalDateTime.now();

        //方法开始的时间
        long begin = System.currentTimeMillis();
        //执行原始方法
        Object result = pjp.proceed();
        Result re=(Result) result;
        long end = System.currentTimeMillis();


        //存储登录是否成功的状态
        short isSuccess;
        if (re.getCode()==0){
            isSuccess=0;
            empLoginMapper.insertEmpLogin(new EmpLoginLog(null,username,password,loginTime,isSuccess,null,end-begin));
        }else {
            isSuccess=1;
            LoginInfo data = (LoginInfo)re.getData();
            String token = data.getToken();
            empLoginMapper.insertEmpLogin(new EmpLoginLog(null,username,password,loginTime,isSuccess,token,end-begin));
        }

        return result;
    }
}
